package com.cal.calonecal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cal.calonecal.common.Response;
import com.cal.calonecal.mapper.*;
import com.cal.calonecal.pojo.entity.*;
import com.cal.calonecal.service.IPaperService;
import com.cal.calonecal.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 76004
 * @apiNote
 * @date 2023/6/17 11:12
 */
@Service
public class PaperServiceImpl implements IPaperService {
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private UserUtil userUtil;

    @Autowired
    private ChooseMapper chooseMapper;

    @Autowired
    private ProblemMapper problemMapper;

    @Autowired
    private TagProblemMapper tagProblemMapper;
    @Override
    public Response<Void> add(Paper paper) {
        paper.setCreateTime(new Date());
        paper.setUserId(userUtil.getUserId());
        paper.setClassId(-1L);
        paperMapper.insert(paper);
        paper.getProblemIds().stream().peek(problemId -> {
            Problem problem = problemMapper.selectById(problemId);
            System.out.println(problem);
            problem.setId(null);
            problem.setStatus(1);
            problem.setPaperId(paper.getId());
            problemMapper.insert(problem);
            //新增选项
            chooseMapper.selectList(new QueryWrapper<Choose>().eq("problem_id", problemId))
                    .stream().peek(choose -> {
                        choose.setProblemId(problem.getId());
                        choose.setStatus(1);
                        chooseMapper.insert(choose);
                    }).collect(Collectors.toList());
            //新增标签
            tagProblemMapper.selectList(new QueryWrapper<TagProblem>().eq("problem_id", problemId)).stream().peek(tagProblem -> {
                tagProblem.setId(null);
                tagProblem.setProblemId(problem.getId());
                tagProblemMapper.insert(tagProblem);
            }).collect(Collectors.toList());
        }).collect(Collectors.toList());
        return Response.success();
    }

    @Override
    public Response<Void> delete(long id) {
        paperMapper.deleteById(id);
        return Response.success();
    }

    @Override
    public Response<Void> update(Paper paper) {
        paperMapper.updateById(paper);
        return Response.success();
    }

    @Override
    public Response<Paper> selectById(Long id) {
        Paper paper = paperMapper.selectById(id);
        paper.setProblems(problemMapper.selectList(new QueryWrapper<Problem>().eq("paper_id", id)).stream().map(problem -> {
            problem.setTags(tagProblemMapper.selectList(new QueryWrapper<TagProblem>().eq("problem_id", problem.getId())).stream().map(TagProblem::getName).collect(Collectors.toList()));
            problem.setChooses(chooseMapper.selectList(new QueryWrapper<Choose>().eq("problem_id", problem.getId())));
            return problem;
        }).collect(Collectors.toList()));
        paper.setProblemNum(paper.getProblems().size());
        return Response.success();
    }

    @Override
    public Response<IPage<Paper>> selectByUserId(Integer pageNum, Integer pageSize) {
        return Response.success(paperMapper.selectPage(new Page<Paper>(pageNum, pageSize),
                new QueryWrapper<Paper>().eq("user_id", userUtil.getUserId()).eq("class_id", -1L)));
    }

    @Override
    public Response<IPage<Paper>> selectPage(Integer pageNum, Integer pageSize) {
        return Response.success(paperMapper.selectPage(new Page<Paper>(pageNum, pageSize), null));
    }

    @Override
    public Response<Paper> judge(Paper paper) {
        paper.setProblems(paper.getProblems().stream().map(problem -> {
            int isCorrect = 1;
            //答案校验
            if(problem.getAns().equals(problem.getAnswer().getUserAns())) {
                isCorrect = 1;
            } else {
                if (problem.getAns().length() < problem.getAnswer().getUserAns().length()) {
                    isCorrect = 0;
                } else {
                    for(int i = 0; i < problem.getAns().length(); i++) {
                        if (problem.getAns().charAt(i) != problem.getAnswer().getUserAns().charAt(i)) {
                            isCorrect = 0;
                            break;
                        }
                    }
                }
            }
            problem.getAnswer().setIsCorrect(isCorrect);
            //存储作答记录
            Answer answer = problem.getAnswer();
            answer.setPaperId(paper.getId());
            answer.setUserId(userUtil.getUserId());
            answer.setProblemId(problem.getId());
            answerMapper.insert(answer);
            return problem;
        }).collect(Collectors.toList()));
        return Response.success(paper);
    }

    @Override
    public Response<IPage<Paper>> selectUserPaperRecords(Integer pageNum, Integer pageSize) {
        IPage<Paper> page = paperMapper.selectPage(new Page<Paper>(pageNum, pageSize),
                new QueryWrapper<Paper>().eq("user_id", userUtil.getUserId()));
        page.setRecords(page.getRecords().stream().map(paper -> {
            //查询试卷题目
            List<Problem> problems = problemMapper.selectList(new QueryWrapper<Problem>()
                    .eq("paper_id", paper.getId())).stream().map(problem -> {
                //查询题目选项
                problem.setChooses(chooseMapper.selectList(new QueryWrapper<Choose>().eq("problem_id", problem.getId())));
                return problem;
            }).collect(Collectors.toList());
            paper.setProblems(problems);
            return paper;
        }).collect(Collectors.toList()));
        return Response.success(page);
    }

        @Override
        public Response<Paper> selectUserRecord(Long paperId) {
            Paper paper= paperMapper.selectById(new QueryWrapper<Paper>().eq("paper_id", paperId));
            paper.setProblems(problemMapper.selectList(new QueryWrapper<Problem>().eq("paper_id", paperId)).stream().map(problem -> {
                problem.setChooses(chooseMapper.selectList(new QueryWrapper<Choose>().eq("problem_id", problem.getId())));
                problem.setAnswer(answerMapper.selectOne(new QueryWrapper<Answer>().eq("problem_id", problem.getId())
                        .eq("user_id", userUtil.getUserId())));
                return problem;
            }).collect(Collectors.toList()));
            return Response.success(paper);
        }

    @Override
    public Response<Void> publish(Long paperId, Long classId) {
        Paper paper = paperMapper.selectById(paperId);
        paper.setCreateTime(new Date());
        paper.setUserId(userUtil.getUserId());
        paper.setClassId(classId);
        paper.setId(null);
        paperMapper.insert(paper);
        paper.getProblemIds().stream().peek(problemId -> {
            Problem problem = problemMapper.selectById(problemId);
            problem.setId(null);
            problem.setStatus(2);
            problem.setPaperId(paper.getId());
            problemMapper.insert(problem);
            //新增选项
            chooseMapper.selectList(new QueryWrapper<Choose>().eq("problem_id", problemId))
                    .stream().peek(choose -> {
                        choose.setProblemId(problem.getId());
                        choose.setStatus(2);
                        chooseMapper.insert(choose);
                    }).collect(Collectors.toList());
            //新增标签
            tagProblemMapper.selectList(new QueryWrapper<TagProblem>().eq("problem_id", problemId)).stream().peek(tagProblem -> {
                tagProblem.setTagId(null);
                tagProblem.setProblemId(problem.getId());
                tagProblemMapper.insert(tagProblem);
            }).collect(Collectors.toList());
        }).collect(Collectors.toList());
        return Response.success();
    }

    @Override
    public Response deleteProblemInPaper(Long problemId) {
        chooseMapper.delete(new QueryWrapper<Choose>().eq("problem_id", problemId));
        tagProblemMapper.delete(new QueryWrapper<TagProblem>().eq("problem_id", problemId));
        problemMapper.deleteById(problemId);
        return Response.success();
    }

    @Override
    public Response addProblem2Paper(Long problemId, Long paperId) {
        Problem problem = problemMapper.selectById(problemId);
        problem.setId(null);
        problem.setStatus(1);
        problem.setPaperId(paperId);
        problemMapper.insert(problem);
        //新增选项
        chooseMapper.selectList(new QueryWrapper<Choose>().eq("problem_id", problemId))
                .stream().peek(choose -> {
                    choose.setProblemId(problem.getId());
                    choose.setStatus(1);
                    chooseMapper.insert(choose);
                }).collect(Collectors.toList());
        //新增标签
        tagProblemMapper.selectList(new QueryWrapper<TagProblem>().eq("problem_id", problemId)).stream().peek(tagProblem -> {
            tagProblem.setTagId(null);
            tagProblem.setProblemId(problem.getId());
            tagProblemMapper.insert(tagProblem);
        }).collect(Collectors.toList());
        return Response.success();
    }


}
